from datetime import date

from django.shortcuts import render
from utils.goods import get_categories, get_contents
from django.views import View
from django.http import JsonResponse, HttpResponse


# Create your views here.
class IndexView(View):
    def get(self, request):
        context = {
            'categories': get_categories(),
            'contents': get_contents()
        }

        return render(request, 'index.html', context=context)


"""
需求:
        实现列表页面的数据获取
前端:
        list/115/skus/?page=1&page_size=5&ordering=-create_time

后端:
    
        请求:
                GET     
        业务逻辑:
                1. 接收参数
                2. 提起参数
                3. 验证参数
                4. 查询数据 
                    4.1 根据分类id查询数据
                    4.2 查询的数据排序
                    4.3 查询的数据分页
                5. 返回响应
        返回响应:
            "code": 0,
            "errmsg": "ok",
            "list": [
                {
                    "id": 16,
                    "default_image_url": "http://qmkds4f73.hnbkt.clouddn.com/CtM3BVrRdPeAXNDMAAYJrpessGQ9777651.png",
                    "name": "华为 HUAWEI P10 Plus 6GB+128GB 曜石黑 移动联通电信4G手机 双卡双待",
                    "price": "3788.00"
                },
                ...
            ],
            "count": 3
"""

from apps.goods.models import SKU


class ListSKUView(View):

    def get(self, request, category_id):
        # 1. 接收数据
        query_params = request.GET
        # 2. 提取数据
        ordering = query_params.get('ordering', '-createtime')
        page_size = query_params.get('page_size', 5)
        page = query_params.get('page', 1)
        # 3. 验证参数
        # 4. 查询数据
        #     4.1 根据分类id查询数据
        #     4.2 查询的数据排序
        skus = SKU.objects.filter(category=category_id).order_by(ordering)
        #     4.3 查询的数据分页
        from django.core.paginator import Paginator
        # 1. 创建分页类
        instance = Paginator(skus, page_size)
        # 2. 获取指定页  数据
        page_skus = instance.page(page)
        # 3. 获取总页数
        total = instance.num_pages
        data_dict = []
        for item in page_skus.object_list:
            data_dict.append({
                'id': item.id,
                'name': item.name,
                'price': item.price,
                'default_image_url': item.default_image.url
            })

        # 获取三级分类
        from apps.goods.models import GoodsCategory
        from utils.goods import get_breadcrumb
        category = GoodsCategory.objects.get(id=category_id)
        breadcrumb = get_breadcrumb(category)

        # 5. 返回响应
        return JsonResponse({
            "code": 0,
            "errmsg": "ok",
            "breadcrumb": breadcrumb,
            "list": data_dict,
            "count": total
        })


class HOTSKUView(View):
    def get(self, request, category_id):
        skus = SKU.objects.filter(category_id=category_id).order_by('-sales')[0:2]
        data_list = []
        for item in skus:
            data_list.append({
                'id': item.id,
                'name': item.name,
                'price': item.price,
                'default_image_url': item.default_image.url  # 注意 调用url 因为要把图片 拼接 七牛云的外链
            })

        return JsonResponse({
            "code": "0",
            "errmsg": "OK",
            "hot_skus": data_list})


class DetailView(View):
    def get(self, request, sku_id):
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '没有此商品'})

        # 2. 获取分类数据
        from utils.goods import get_categories
        categories = get_categories()
        # 3. 获取面包屑数据
        from utils.goods import get_breadcrumb
        breadcrumb = get_breadcrumb(sku.category)
        # 4. 获取规格和选项
        from utils.goods import get_goods_specs
        specs = get_goods_specs(sku)

        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': specs
        }

        return render(request, 'detail.html', context=context)


"""
需求:
    统计一天内该类别的商品被访问的次数。


前端:
        发送请求,传递 分类id

后端:

    请求:
            POST        /detail/visit/分类id/

    业务逻辑:

            1. 根据分类id查询分类数据
            2. 根据统计模型 查询当前的 分类记录 是否存在
            3. 如果不存在 则新增
            4. 如果存在,则访问量+1
            5. 返回响应
    响应:

            code: 0
"""
from apps.goods.models import GoodsCategory, GoodsVisitCount


class CategoryVisitView(View):
    def post(self, request, category_id):
        # 1.根据分类id查询分类数据
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '分类信息错误'})

        # 2. 根据统计模型 查询当前的 分类记录 是否存在
        today = date.today()
        try:
            gvc = GoodsVisitCount.objects.get(category=category,
                                              date=today)
        except GoodsVisitCount.DoesNotExist:
            # 3. 如果不存在 则新增
            GoodsVisitCount.objects.create(
                category=category,
                count=1,
                date=today
            )
        else:
            # 4. 如果存在,则访问量+1
            gvc.count += 1
            gvc.save()

        # 5. 返回响应
        return JsonResponse({'code': 0, 'errmsg': 'ok'})
